package aame.controle.manterCliente;

import java.util.List;
import aame.AaME;
import aame.AaMEPck.R;
import aame.bean.Cliente;
import aame.bean.Endereco;
import aame.dao.SQLiteHelper;
import aame.excecao.Excecao;
import aame.negocio.manterCliente.ClienteNegocio;
import aame.negocio.manterEndereco.EnderecoNegocio;
import android.app.ListActivity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class BuscarControleCliente extends ListActivity{

	private SQLiteDatabase db = null;
	public static Cliente cliente;
	public static Endereco endereco;
	
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		cliente = null;
		endereco = null;
		
		db = new SQLiteHelper(this).getWritableDatabase();
        setContentView(R.layout.b_buscar_cliente);

		ListView lv = getListView();
        lv.setTextFilterEnabled(true);
        		
		setListAdapter(new ArrayAdapter(this, R.layout.b_layout_lista, R.id.listaClientes, buscarListaClienteControle()));
	}
		
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
	
		cliente = (Cliente) this.getListAdapter().getItem(position);
		buscarEnderecoCliente();
		db.close();
		Intent i = new Intent(this, AlterarExcluirControleCliente.class);
    	startActivity(i);
		finish();
	}
			
	/***************************Teclas para voltar/ir****************************/
	
	public void irCadastrarCliente(View view){
		db.close();
		Intent i = new Intent(this, CadastrarControleCliente.class);
    	startActivity(i);
    	finish();
    }
	
	public void irControlarRegistros(View view){
		db.close();
		Intent i = new Intent(this, AaME.class);
    	startActivity(i);
    	finish();
    }
	
		
	public List<Cliente> buscarListaClienteControle(){

		List<Cliente> clientes = null;
		
		try {
			clientes = new ClienteNegocio().buscarListaClienteNegocio(db);
		} catch (Excecao e) {
			Toast.makeText(this, e.getMsgError(), Toast.LENGTH_SHORT).show();
			e.printStackTrace();
		}
		return clientes;
		
	}
	
	public void buscarEnderecoCliente(){
		try {
			endereco = new EnderecoNegocio().buscarEndereco(db, cliente.getFkIdEndereco());
		} catch (Excecao e) {
			Toast.makeText(this, e.getMsgError(), Toast.LENGTH_SHORT).show();
			e.printStackTrace();
			return;
		}
	}
}
